package com.ch.light.web.service.impl;

import com.ch.light.mybatis.ParamFilter;
import com.ch.light.web.mapper.WebLogMapper;
import com.ch.light.web.model.WebLog;
import com.ch.light.web.service.WebLogService;
import com.github.pagehelper.PageHelper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;
import tk.mybatis.mapper.entity.Example;

import java.util.List;
import java.util.Map;

import static com.google.common.base.Preconditions.checkArgument;
import static com.google.common.base.Preconditions.checkNotNull;

@Service
public class WebLogServiceImpl implements WebLogService {

    @Autowired
    private WebLogMapper webLogMapper;

    @Override
    public void add(WebLog webLog) {
        checkNotNull(webLog, "操作日志不能为空");
        webLogMapper.insertSelective(webLog);
    }

    @Override
    public void delete(Long[] ids) {
        checkArgument(ids != null && ids.length > 0, "操作日志编号不能为空");
        for (Long id : ids) {
            webLogMapper.deleteByPrimaryKey(id);
        }
    }

    @Override
    public void update(WebLog t) {
        checkNotNull(t, "操作日志不能为空");
        webLogMapper.updateByPrimaryKeySelective(t);
    }

    @Override
    public List<WebLog> getList(ParamFilter paramFilter) {
        int pageNum = paramFilter.getPage().getPageNo();
        int pageSize = paramFilter.getPage().getPageSize();
        PageHelper.startPage(pageNum, pageSize, true, false, false);
        Example example = new Example(WebLog.class);
        Map<String, Object> param = paramFilter.getParam();
        if (param != null) {
            Example.Criteria criteria = example.createCriteria();
            String username = (String) param.get("username");
            String createAt = (String) param.get("createAt");

            if (!StringUtils.isEmpty(username)) {
                criteria.andEqualTo("username", username);
            }
            if (!StringUtils.isEmpty(createAt)) {
                criteria.andCondition("DATE_FORMAT(CREATE_AT, '%Y-%m-%d') = '" + createAt + "'");
            }
        }
        //PageHelper.orderBy("CREATE_AT DESC");
        example.setOrderByClause("CREATE_AT DESC");
        return webLogMapper.selectByExample(example);
    }
}
